#include <iostream>
#include <vector>
#include <string>
#include <unistd.h>
#include <cstdio>
#include <sys/types.h>
#include <sys/wait.h>

enum{
    OPEN_FILE_ERROR = 1,
    OK = 0,
};

const std::string gsep = " ";
std::vector<int> data;

int SaveBegin()
{
    std::string name = std::to_string(time(nullptr));
    name += ".backup";
    //打开文件
    FILE *fp = fopen(name.c_str(),"w");
    //判断文件打开是否失败
    if(fp == nullptr) return OPEN_FILE_ERROR;
    //文件打开成功 ，备份
    std::string dataStr;//储存vector里面值
    for(auto d: data)
    {
        dataStr += std::to_string(d);
        dataStr += gsep;//加空格符
    }
    //把dataStr数据，放入fp文件中
    fputs(dataStr.c_str(),fp);
    //关闭文件
    fclose(fp);
    return OK;
}

void Save()
{
    pid_t id = fork();
    if(id == 0)//child
    {
        //备份任务
        int code = SaveBegin();
        exit(code);
    }
    //父进程
    int status = 0;
    //等待回收子进程
    pid_t rid = waitpid(id,&status,0);
    if(rid > 0)//成功退出
    {
        int code = WEXITSTATUS(status);//获取退出码
        if(code == 0) printf("备份成功！,exit code: %d\n",code);
        else printf("备份失败！,exit code: %d\n",code);
    }
    else//异常退出
    {
        perror("waitpid");
    }
}

int main()
{
    int cnt = 1;
    while(true)
    {
        data.push_back(cnt++);
        sleep(1);

        if(cnt % 10 == 0)
        {
            Save();
        }
    }
    return 0;
}